import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'
import { Button, Checkbox, Toast, Loading } from '@taroify/core'
import recipeService from '../utils/recipeService'
import './ingredients.scss'

// 预定义食材分类
const predefinedCategories = {
  vegetables: [
    '西红柿',
    '土豆',
    '茄子',
    '青椒',
    '西兰花',
    '胡萝卜',
    '木耳',
    '竹笋',
    '豆腐',
    '青瓜',
    '丝瓜',
    '香菜',
    '茴香',
    '芹菜',
    '白菜',
    '菠菜',
    '生菜',
    '空心菜',
    '韭菜',
    '豆芽',
    '莲藕',
    '山药',
    '南瓜',
    '冬瓜',
    '苦瓜',
    '黄瓜',
    '豆角',
    '四季豆',
    '洋葱',
    '蒜苗',
    '韭黄',
    '油菜',
    '芥菜',
    '苋菜',
    '茼蒿'
  ],
  meat: [
    '猪肉',
    '肉末',
    '排骨',
    '五花肉',
    '牛肉',
    '瘦肉',
    '猪肝',
    '火腿',
    '腊肉',
    '培根',
    '猪蹄',
    '猪心',
    '猪肚',
    '猪肠',
    '羊肉',
    '羊排',
    '鸡肉',
    '鸡翅',
    '鸡腿',
    '鸡胸肉',
    '鸭肉',
    '鸭翅',
    '鸭腿',
    '鹅肉',
    '兔肉'
  ],
  seafood: [
    '虾',
    '海参',
    '鱼',
    '带鱼',
    '鲈鱼',
    '鲫鱼',
    '草鱼',
    '鲤鱼',
    '鲢鱼',
    '螃蟹',
    '扇贝',
    '蛤蜊',
    '蛏子',
    '海带',
    '紫菜',
    '鱿鱼',
    '墨鱼',
    '章鱼',
    '海螺',
    '海蜇',
    '海虾',
    '基围虾',
    '龙虾',
    '鲍鱼',
    '生蚝'
  ],
  grains: [
    '小米',
    '面条',
    '红薯粉',
    '面粉',
    '糯米',
    '玉米',
    '燕麦',
    '薏米',
    '黑米',
    '糙米',
    '米粉',
    '河粉',
    '年糕',
    '包子',
  ],
  others: [
    '鸡蛋',
    '米饭',
    '油',
    '豆干',
    '花生油',
    '生粉',
    '豆腐皮',
    '腐竹',
    '豆皮',
    '豆泡',
    '豆筋',
    '豆芽',
    '豆酱',
    '豆奶',
    '豆浆',
    '豆花',
  ]
}

// 从菜谱数据中提取所有食材并分类
const getIngredientsByCategory = (recipeData) => {
  // 从所有菜谱中提取食材
  const allIngredients = new Set()
  recipeData.forEach((recipe) => {
    recipe.ingredients.forEach((ingredient) => {
      allIngredients.add(ingredient)
    })
  })

  // 复制预定义分类
  const categories = JSON.parse(JSON.stringify(predefinedCategories))

  // 将未分类的食材放入其他类别
  const categorizedIngredients = Object.values(categories).flat()
  const otherIngredients = [...allIngredients].filter((item) => !categorizedIngredients.includes(item))
  categories.others = [...new Set([...categories.others])]

  return categories
}

const Ingredients = () => {
  const [categories, setCategories] = useState({})
  const [selectedIngredients, setSelectedIngredients] = useState([])
  const [isToastOpen, setIsToastOpen] = useState(false)
  const [toastMessage, setToastMessage] = useState('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [recipeData, setRecipeData] = useState([])

  // 加载食谱数据和分类食材
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        // 从云端获取食谱数据
        const data = await recipeService.getRecipes()
        setRecipeData(data)

        // 分类食材
        const ingredientCategories = getIngredientsByCategory(data)
        setCategories(ingredientCategories)
      } catch (err) {
        console.error('获取食谱数据失败:', err)
        setError('加载食材失败，请重试')
        Taro.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  // 处理食材选择变化
  const handleSelectionChange = (values) => {
    setSelectedIngredients(values)
  }

  // 生成菜谱
  const generateRecipes = () => {
    if (selectedIngredients.length === 0) {
      setToastMessage('请至少选择一种食材')
      setIsToastOpen(true)
      return
    }

    // 根据选中的食材过滤菜谱
    const matchedRecipes = recipeData.filter((recipe) =>
      selectedIngredients.some((ingredient) => recipe.ingredients.includes(ingredient))
    )

    if (matchedRecipes.length === 0) {
      setToastMessage('未找到相关菜谱，请更换食材')
      setIsToastOpen(true)
      return
    }

    // 将匹配的菜谱ID传递给搜索页面
    const recipeIds = matchedRecipes.map((recipe) => recipe.id)
    Taro.navigateTo({
      url: `/pages-recipe/search?ingredients=${encodeURIComponent(JSON.stringify(recipeIds))}`
    })
  }

  // 清空选择
  const clearSelection = () => {
    setSelectedIngredients([])
  }

  // 渲染分类食材
  const renderCategoryIngredients = (categoryName, ingredients) => {
    return (
      <View className='category-section' key={categoryName}>
        <View className='category-title'>
          <Text>{getCategoryDisplayName(categoryName)}</Text>
        </View>
        <View className='ingredients-list'>
          <Checkbox.Group value={selectedIngredients} onChange={handleSelectionChange}>
            {ingredients.map((ingredient) => (
              <Checkbox name={ingredient} key={ingredient} className='ingredient-item'>
                {ingredient}
              </Checkbox>
            ))}
          </Checkbox.Group>
        </View>
      </View>
    )
  }

  // 获取分类的显示名称
  const getCategoryDisplayName = (categoryKey) => {
    const displayNames = {
      vegetables: '蔬菜类',
      meat: '肉类',
      seafood: '海鲜类',
      grains: '谷物类',
      others: '其他食材'
    }
    return displayNames[categoryKey] || categoryKey
  }

  return (
    <View className='ingredients-page'>
      {/* 加载状态 */}
      {loading && (
        <View className='loading-container'>
          <Loading type='spinner' />
          <Text className='loading-text'>正在加载食材数据...</Text>
        </View>
      )}

      {/* 错误状态 */}
      {error && !loading && (
        <View className='error-container'>
          <Text className='error-text'>{error}</Text>
          <Button
            color='primary'
            size='small'
            onClick={() => {
              setError(null)
              setLoading(true)
              recipeService
                .getRecipes()
                .then((data) => {
                  setRecipeData(data)
                  setCategories(getIngredientsByCategory(data))
                })
                .catch((err) => {
                  console.error('重试失败:', err)
                  setError('重试加载失败，请稍后再试')
                })
                .finally(() => {
                  setLoading(false)
                })
            }}>
            重试
          </Button>
        </View>
      )}

      {/* 主要内容 */}
      {!loading && !error && (
        <>
          <View className='header'>
            <Text className='title'>食材选择</Text>
            <Text className='subtitle'>选择你家有的食材，为你推荐适合的菜谱</Text>
          </View>

          <View className='selected-count'>
            已选择: <Text className='count'>{selectedIngredients.length}</Text> 种食材
            {selectedIngredients.length > 0 && (
              <Text className='clear-btn' onClick={clearSelection}>
                清空
              </Text>
            )}
          </View>

          <ScrollView scrollY className='categories-container'>
            {Object.entries(categories).map(([category, ingredients]) =>
              renderCategoryIngredients(category, ingredients)
            )}
          </ScrollView>

          <View className='footer'>
            <Button
              color='primary'
              block
              className='generate-btn'
              disabled={selectedIngredients.length === 0}
              onClick={generateRecipes}>
              生成菜谱推荐
            </Button>
          </View>

          <Toast open={isToastOpen} onClose={() => setIsToastOpen(false)}>
            {toastMessage}
          </Toast>
        </>
      )}
    </View>
  )
}

export default Ingredients
